{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.datasets import make_classification\n",
    "from sklearn.base import clone, BaseEstimator, TransformerMixin, ClassifierMixin\n",
    "\n",
    "\n",
    "class StackingClassifier(BaseEstimator, ClassifierMixin, TransformerMixin):\n",
    "    \n",
    "    def __init__(self, classifiers):\n",
    "        self.classifiers = classifiers\n",
    "        self.meta_classifier = DecisionTreeClassifier()\n",
    "\n",
    "    def fit(self, X, y):\n",
    "        for clf in self.classifiers:            \n",
    "            clf.fit(X, y)\n",
    "\n",
    "        self.meta_classifier.fit(self._get_meta_features(X), y)        \n",
    "        return self\n",
    "\n",
    "    def _get_meta_features(self, X):\n",
    "        probas = np.asarray([clf.predict_proba(X) for clf in self.classifiers])\n",
    "        return np.concatenate(probas, axis=1)\n",
    "        \n",
    "    def predict(self, X):\n",
    "        return self.meta_classifier.predict(self._get_meta_features(X))\n",
    "\n",
    "    def predict_proba(self, X):\n",
    "        return self.meta_classifier.predict_proba(self._get_meta_features(X))\n",
    "\n",
    "\n",
    "X, y = make_classification(\n",
    "    n_samples=1000, n_features=50, n_informative=30, n_clusters_per_class=3, random_state=11)\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=11)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Logistic regression accuracy: 0.816\n",
      "KNN accuracy: 0.836\n"
     ]
    }
   ],
   "source": [
    "lr = LogisticRegression()\n",
    "lr.fit(X_train, y_train)\n",
    "print('Logistic regression accuracy: %s' % lr.score(X_test, y_test))\n",
    "\n",
    "knn_clf = KNeighborsClassifier()\n",
    "knn_clf.fit(X_train, y_train)\n",
    "print('KNN accuracy: %s' % knn_clf.score(X_test, y_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Stacking classifier accuracy: 0.852\n"
     ]
    }
   ],
   "source": [
    "base_classifiers = [lr, knn_clf]\n",
    "stacking_clf = StackingClassifier(base_classifiers)\n",
    "stacking_clf.fit(X_train, y_train)\n",
    "print('Stacking classifier accuracy: %s' % stacking_clf.score(X_test, y_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
